import json
import chardet


class FileExtend:

    # 按修改时间从早排序获取文件
    @staticmethod
    def readFile(file_name):
        encoding = FileExtend.GetFileEncoding(file_name)
        with open(file_name, 'r', encoding=encoding) as f:
            content = f.read()
        return content

    @staticmethod
    def readJsonFile(file_name):
        content = FileExtend.readFile(file_name)
        return json.loads(content)

    @staticmethod
    def GetFileEncoding(file_name):
        with open(file_name, 'rb') as f:
            data = f.read()
            return chardet.detect(data)['encoding']

    @staticmethod
    def writeJsonFile(file, content):
        with open(file, 'w', encoding='utf-8') as f:
            f.write(json.dumps(content))

    @staticmethod
    def appendFile(file, content: str):
        with open(file, 'a', encoding='utf-8') as f:
            f.write(content)

    @staticmethod
    def writeFile(file, content: str):
        with open(file, 'w', encoding='utf-8') as f:
            f.write(content)

    @staticmethod
    def writeFileBytes(file, content: bytes):
        with open(file, 'wb') as f:
            f.write(content)

    @staticmethod
    def readFileBytes(file):
        with open(file, 'rb') as f:
            content = f.read()
        return content
